package com.ygq.blog.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * LogAspect
 * 日志 AOP
 *
 * @author Yin Guiqing
 */
@Aspect
@Component
public class LogAspect {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 切点表达式
     */
    @Pointcut("execution(* com.ygq.blog.controller.*.*(..))")
    public void log() {
    }

    /**
     * 前置通知
     *
     * @param joinPoint 封装了 Spring AOP 中切面方法的信息
     */
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String uri = null;
        String ip = null;
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            uri = request.getRequestURI();
            ip = request.getRemoteAddr();
        }
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." +
                joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(uri, ip, classMethod, args);

        logger.info("***** doBefore *****");
        logger.info("Request : {}", requestLog);
    }

    @After("log()")
    public void doAfter() {
        logger.info("***** doAfter *****");
    }

    @AfterReturning(pointcut = "log()", returning = "result")
    public void doAfterReturn(Object result) {
        logger.info("***** doAfterReturn -> Result : {} *****", result);
    }

    /**
     * 内部类，封装请求日志
     */
    private static class RequestLog {
        // 请求的 uri
        private String uri;
        // 请求者的 ip
        private String ip;
        // 请求的方法
        private String classMethod;
        // 请求的参数
        private Object[] args;

        public RequestLog(String uri, String ip, String classMethod, Object[] args) {
            this.uri = uri;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "RequestLog{" +
                    "uri='" + uri + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }
}
